package timing.ukulele.seal.util;

import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;

public final class PdfUtil {
    public static void pdfAddImage(InputStream pdfFile, OutputStream composition, Image image, int page, float positionX, float positionY, float width, float height) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        //合成后的文件
        try {
            //解决PdfReader not opened with owner password
            PdfReader.unethicalreading = true;
            reader = new PdfReader(pdfFile);
            stamper = new PdfStamper(reader, composition);
            PdfContentByte over = stamper.getOverContent(page);
            //签名图片
            over.saveState();
            float docHeight = over.getPdfDocument().getPageSize().getTop();
            System.out.println("页面高度：" + docHeight);
            // 前端将pdf缩放了1.5倍。坐标系是左下角，而前端的坐标系是左上角
//            image.setAbsolutePosition(positionX / 1.5f, docHeight - 72 - positionY / 1.5f - height / 3f);  //设置图片位置
            image.setAbsolutePosition(positionX / 1.5f, docHeight - positionY / 1.5f - height / 1.5f);  //设置图片位置
            image.scaleAbsolute(width / 1.5f, height / 1.5f);  //设置图片大小
            over.addImage(image);  //将图片添加到pdf文件
            over.restoreState();
            stamper.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (reader != null)
                reader.close();
        }
    }

    public static void addSingleWaterMark(String pdfFilePath, String outputFilePath) {
        try {
            // 原PDF文件
            PdfReader reader = new PdfReader(pdfFilePath);
            // 输出的PDF文件内容
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilePath));
            // 字体 来源于 itext-asian JAR包
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", true);
            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);
            int totalPage = reader.getNumberOfPages() + 1;
            for (int i = 1; i < totalPage; i++) {
                // 内容下层
                PdfContentByte content = stamper.getUnderContent(i);
                content.beginText();
                // 字体添加透明度
                content.setGState(gs);
                // 添加字体大小等
                content.setFontAndSize(baseFont, 50);
                // 添加范围
                content.setTextMatrix(70, 200);
                // 具体位置 内容 旋转多少度 共360度
                content.showTextAligned(Element.ALIGN_CENTER, "待审核文件", 300, 350, 300);
                content.showTextAligned(Element.ALIGN_TOP, "待审核文件", 100, 100, 5);
                content.showTextAligned(Element.ALIGN_BOTTOM, "待审核文件", 400, 400, 75);
                content.endText();
            }
            // 关闭
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addWaterMark(InputStream inPdf, OutputStream outPdf, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inPdf);
            PdfStamper stamper = new PdfStamper(reader, outPdf);
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//            BaseFont base = BaseFont.createFont("simsun.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.1f);//改透明度
            gs.setStrokeOpacity(0.1f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            label.setText(waterMarkName);
            PdfContentByte under;
            Rectangle pageRect;
            FontMetrics metrics;
            int interval = -5;
            int textH;
            int textW;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);//在内容上方加水印
//                under = stamper.getUnderContent(i);//在内容下方加水印
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 20);
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, width - textW,
                                height - textH, 30);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        //pdf文件存放在E盘
        File file = new File("E:\\tmp\\contract.pdf");
        FileInputStream pdf = new FileInputStream(file);
        FileOutputStream outputStream = new FileOutputStream("E:\\tmp\\contract_sign.pdf");
        Image contractSealImg = Image.getInstance("E:\\tmp\\seal.png");
        PdfUtil.pdfAddImage(pdf, outputStream, contractSealImg, 8, 175, 570, 180, 180);

        File inPdfFile = new File("E:\\tmp\\contract_sign.pdf");
        FileInputStream inPdf = new FileInputStream(inPdfFile);
        FileOutputStream outPdf = new FileOutputStream("E:\\tmp\\contract_sign_watermark.pdf");
        PdfUtil.addWaterMark(inPdf, outPdf, "待审核文件");
    }
}
